﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Module_Debug
{
    public partial class FT2388 : Form
    {
        List<string> lines;
        /// <summary>
        /// ///FT2388  
        /// </summary>
        private double B_x = 0.14;
        private double B_y = 0.06;
        //De_Mura
        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke  
                                      //==============ca310===============
        private double auto_lum;//
        private double auto_x;
        private double auto_y;

        /// <summary>
        /// /auto gamma add 20181031
        /// </summary>
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;

        private ushort[] mygamma_r = new ushort[28];
        private ushort[] mygamma_g = new ushort[28];
        private ushort[] mygamma_b = new ushort[28];

        private int step_h = 12;
        private int step_l = 1;
        //==============ca310===============
        //private int CAS200_Measure_Gray = 255;
        //private int CAS200_Measure_Count = 0;
        //private int CA200_Measure_CE = 0;
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过   
        private byte[] Rec_tmp = new byte[1];//
        private byte[] Rec_tmp1 = new byte[1];//
        private byte[] Send_buf = new byte[1];
        //private byte signal_mode;
        private byte start_trans_flag = 0;
        private byte continueflag = 0;

        private byte[] Driver_IC = new byte[1];
        //private List<string> ImageType;
        private delegate void MonitorSerialPortChangeEventHandler();
        //private MonitorSerialPortChangeEventHandler MonitorCom;
        //private int serialPortStatus;

        CRC16 CRCData = new CRC16();

        frmMain MainForm = null;
        public FT2388(frmMain Frm)
        {
            MainForm = Frm;
            InitializeComponent();
        }

        private void Frm_Activated(object sender, EventArgs e)
        {
            if ((MainForm.btnCal_manual.Tag != null) && (Convert.ToString(MainForm.btnCal_manual.Tag) != "0calerr"))
            {
                btnAutoGammas_VTDR6100.Enabled = true;
                txttip.Text += "AutoGamma Enabled." + "\r\n";
            }
        }

        //=================================Timer====Start=========================
        private void T1_Tick(object sender, EventArgs e)
        {
            T1.Enabled = false;
            txttip.Text = txttip.Text + "通讯故障!\r\n";
            txttip.Focus();//获取焦点
            txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
            txttip.ScrollToCaret();//滚动到光标处
        }
        private void T2_Tick(object sender, EventArgs e)
        {

            toolStripStatusLabel2.Text = DateTime.Now.ToString();
        }
        //=================================Timer====end=========================
        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            //if (MainForm.IClosing) return;
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = MainForm.comPort.BytesToRead;
                byte[] buf = new byte[n];

                MainForm.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    if (buffer[0] == 0x0B)          //返回 STM32内部 flash 的配置文件数据
                    {
                        if (buffer.Count >= (Int16)(buffer[2] << 8) + (buffer[3]) + 7)
                        {
                            Rec_tmp = new byte[(Int16)(buffer[2] << 8) + (buffer[3]) + 7];
                            byte[] crcTemp = new byte[(Int16)(buffer[2] << 8) + (buffer[3]) + 7];
                            buffer.CopyTo(0, crcTemp, 0, (Int16)(buffer[2] << 8) + (buffer[3]) + 7);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[(Int16)(buffer[2] << 8) + (buffer[3]) + 7 - 2] != CRCH && buffer[(Int16)(buffer[2] << 8) + (buffer[3]) + 7 - 1] != CRCL) //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, (Int16)(buffer[2] << 8) + (buffer[3]) + 7);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, (Int16)(buffer[2] << 8) + (buffer[3]) + 7);//正确分析一条数据，从缓存中移除数据。
                            }

                        }
                    }
                    else if (buffer[0] == 0xFE)
                    {
                        Rec_tmp = new byte[buffer[2] + 5];
                        byte[] crcTemp = new byte[buffer[2] + 5];
                        buffer.CopyTo(0, crcTemp, 0, buffer[2] + 5);

                        CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                        if (buffer[buffer[2] + 5 - 2] != CRCH && buffer[buffer[2] + 5 - 1] != CRCL)     //CRC校验出错
                        {
                            buffer.RemoveRange(0, buffer.Count);
                        }
                        else
                        {
                            buffer.CopyTo(0, Rec_tmp, 0, buffer[2] + 5);//复制一条完整数据到具体的数据缓存   
                            data_1_catched = true;
                            buffer.RemoveRange(0, buffer[2] + 5);//正确分析一条数据，从缓存中移除数据。
                            if (Rec_tmp[4] == 0)
                                continueflag = 1;
                        }
                    }
                    else if (buffer[0] == 0x55)     //STM32 更新bin文件成功  返回
                    {
                        if (buffer.Count >= (buffer[2] + 5))
                        {
                            Rec_tmp = new byte[(buffer[2] + 5)];
                            byte[] crcTemp = new byte[(buffer[2] + 5)];
                            buffer.CopyTo(0, crcTemp, 0, (buffer[2] + 5));

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[(buffer[2] + 5) - 2] != CRCH && buffer[(buffer[2] + 5) - 1] != CRCL)       //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, (buffer[2] + 5));//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, (buffer[2] + 5));//正确分析一条数据，从缓存中移除数据。
                                switch (Rec_tmp[3])
                                {
                                    case 0x00:
                                        {
                                            start_trans_flag = 1;
                                        }
                                        break;
                                    case 0x01:
                                        {
                                            if (MainForm.comPort.IsOpen == true) MainForm.comPort.Close();
                                        }
                                        break;
                                    case 0x02:
                                        {
                                            start_trans_flag = 0;
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }

                        }
                    }
                    else if (((buffer[0] == 0x1E) || (buffer[0] == 0x0E) || (buffer[0] == 0x0D) || (buffer[0] == 0x0A) || (buffer[0] == 0x09) || (buffer[0] == 0x08) || (buffer[0] == 0x19) || (buffer[0] == 0x29) || (buffer[0] == 0x2A) || (buffer[0] == 0x09) || (buffer[0] == 0x2E) || (buffer[0] == 0x2B) || (buffer[0] == 0x2C) || (buffer[0] == 0x2D) || (buffer[0] == 0x2F) || (buffer[0] == 0x30) || (buffer[0] == 0x31) || (buffer[0] == 0x3C) || (buffer[0] == 0x3D) || (buffer[0] == 0x4A)
                        || (buffer[0] == 0x4C) || (buffer[0] == 0x52)) || (buffer[0] == 0x53) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, Setting.TempRecord.cmdLen);//正确分析一条数据，从缓存中移除数据。 
                            }
                        }
                    }
                    else
                        buffer.RemoveRange(0, buffer.Count);
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        T1.Enabled = false; //停止超时计数

                        //------------------------------------------------------------------------------------------------------------------------

                        ////---------------------------------------------------RM67160/RM67162/RM69310---------------------------------------
                        if ((Rec_tmp[0] == 0x0E) || (Rec_tmp[0] == 0x1E) || (Rec_tmp[0] == 0x52))  //RM67160/RM67162/RM69310
                        {
                            string tmp = "";
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            txttip.Text = txttip.Text + "寄存器\t写 OK！\r\n";
                                    }
                                    break;

                                case 0x02:
                                    {

                                        {

                                            tmp = String.Format("{0:X2}", Rec_tmp[4]);//16进制
                                            FT2388_txtRegData.Text = tmp;
                                            txttip.Text = txttip.Text + "寄存器\t读 OK！\r\n";
                                        }
                                    }
                                    break;
                                case 0x03://///write gamma ok  RM69310
                                    txttip.Text = txttip.Text + "寄gamma存器\t写 OK！\r\n";
                                    break;

                                case 0x04://///read gamma ok  RM69310
                                    {
                                        txttip.Text = txttip.Text + "读gamma寄存器\t 读 OK！\r\n";
                                    }
                                    break;

                                case 0x05://///write otp ok  RM69310
                                    txttip.Text = txttip.Text + "OTP  \t  写 OK！\r\n";
                                    break;

                                case 0x06://///read otp ok  RM69310
                                    txttip.Text = txttip.Text + "OTP  \t  Read OK！\r\n";

                                    tmp = String.Format("{0:X2}", Rec_tmp[3]);//16进制


                                    break;
                            }
                        }
                        else if (Rec_tmp[0] == 0x53)//////FT2388用的。
                        {
                            string tmp = "";
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            txttip.Text = txttip.Text + "寄存器\t写 OK！\r\n";
                                    }
                                    break;

                                case 0x02:
                                    {

                                        {

                                            for (int i = 3; i < (Rec_tmp[2] + 2); i++)
                                            {
                                                tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                            }


                                            FT2388_txtRegData.Text = tmp;
                                            txttip.Text = txttip.Text + "寄存器\t读 OK！\r\n";
                                        }
                                    }
                                    break;

                                case 0x03://///write gamma ok  RM69310
                                    txttip.Text = txttip.Text + "寄gamma存器\t写 OK！\r\n";
                                    break;

                                case 0x05://///write otp ok  RM69310
                                    txttip.Text = txttip.Text + "OTP  \t  写 OK！\r\n";
                                    break;

                                default:
                                    {

                                    }
                                    break;
                            }
                        }
                        ////---------------------------------------------------Demura----------------------------------------
                        else if (Rec_tmp[0] == 0x2F)  //Demura
                        {
                            if ((Rec_tmp[7] == 0x2E) || (Rec_tmp[7] == 0x3C))   // 297/298/299  //350
                            {
                                if (Rec_tmp[7] == 0x2E)// 297/298/299
                                {
                                    txttip.Text = txttip.Text + "297 298 299\r\n";
                                }
                                else if (Rec_tmp[7] == 0x3C) //350
                                {
                                    txttip.Text = txttip.Text + "350\r\n";
                                }
                                switch (Rec_tmp[1])
                                {
                                    case 0x01:
                                        {
                                            txttip.Text = txttip.Text + "Demura RAM Enable\r\n";
                                        }
                                        break;
                                    case 0x02:
                                        {
                                            txttip.Text = txttip.Text + "Demura RAM Disable\r\n";
                                        }
                                        break;
                                    case 0x03:
                                        {
                                            if (Rec_tmp[7] == 0x2E)// 297/298/299
                                            {
                                                if (Rec_tmp[4] == 0x80)
                                                {
                                                    txttip.Text = txttip.Text + "Demura RAM write Flash complete ! \r\n";
                                                }
                                            }
                                            else if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    txttip.Text = txttip.Text + "Demura RAM write Flash1 complete ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x0A:///350 only
                                        {
                                            if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    txttip.Text = txttip.Text + "Demura RAM write Flash2 complete ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x04:
                                        {
                                            txttip.Text = txttip.Text + "Checksum: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "\r\n";
                                        }
                                        break;
                                    case 0x05:
                                        {
                                            if (Rec_tmp[7] == 0x2E)// 297/298/299
                                            {
                                                if (Rec_tmp[4] == 0x80)
                                                {
                                                    txttip.Text = txttip.Text + "Flash Erase Success ! \r\n";
                                                }
                                            }
                                            else if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    txttip.Text = txttip.Text + "Flash Erase Success ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x06:
                                        {
                                            txttip.Text = txttip.Text + "flash ID: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "," + Rec_tmp[6].ToString("x") + "\r\n";
                                        }
                                        break;
                                    case 0x07:
                                        {
                                            txttip.Text = txttip.Text + "Demura function on \r\n";
                                        }
                                        break;
                                    case 0x08:
                                        {
                                            txttip.Text = txttip.Text + "Demura function off \r\n";
                                        }
                                        break;
                                    case 0x09:
                                        {
                                            txttip.Text = txttip.Text + "Demura OTP complete$ \r\n";
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }

                        txttip.Focus();//获取焦点
                        txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                        txttip.ScrollToCaret();//滚动到光标处
                        if (txttip.Lines.Length > 200) txttip.Text = "";
                    }));
                }
            }
            finally
            {
                Listening = false;

            }
        }
        //=================================LCD cfg function:OLED_Show_Click====Start=================
        private void OLED_Show_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[25];
            Button btnTmp = (Button)sender;
            Setting.TempRecord.cmdLen = 25;
            UInt32 ICS307Temp = 0x00;
            Send_buf[0] = 0x0A; //LCD配置标志
            Send_buf[2] = 0x15; //数据长度
            switch (btnTmp.Name)
            {
                case "btnPatternW":                             //写入Pattern参数
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                        Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                        Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                    }
                    break;
                case "btnred":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //R
                case "btngreen":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0;
                    }
                    break; //G
                case "btnblue":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0xFF;
                    }
                    break; //B
                case "btnwhite":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0xFF;
                    }
                    break; //W
                case "btnblack":
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0;
                        Send_buf[4] = 0;
                        Send_buf[5] = 0;
                    }
                    break; //BL
                default:
                    {
                        Send_buf[1] = 0x07;
                        Send_buf[3] = 0xFF;
                        Send_buf[4] = 0xFF;
                        Send_buf[5] = 0xFF;
                    }
                    break;
            }

            CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
            try
            {
                MainForm.comPort.Write(Send_buf, 0, 25);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            Thread.Sleep(800);
        }

        private void numPatternR_ValueChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternG.Value;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternG.Value;
                numPatternG.Enabled = false;
                numPatternB.Enabled = false;
            }
            else
            {
                numPatternG.Enabled = true;
                numPatternB.Enabled = true;
            }
        }

        //------------------------------------------Demura------------------------------------------------
        private int[] Parttern_FT2388 = new int[27] { 255, 254, 252, 248, 240, 232, 224, 218, 208, 192, 176, 160, 144, 128, 112, 96, 80, 64, 48, 40, 32, 24, 16, 12, 8, 4, 0 };

        private void Msr_CA310()
        {
            MainForm.Msr_CASDK();
            auto_lum = MainForm.CASDK_LUM;
            auto_x = MainForm.CASDK_x;
            auto_y = MainForm.CASDK_y;
        }

        //=================================LCD cfg function: OLED_Show_Click====end=================

        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色
        private double D_x, D_y;

        private int index = 0;

        private int adjust_Rnum = 0;
        private int adjust_Gnum = 0;
        private int adjust_Bnum = 0;

        private double lum_off, x_off, y_off;
        private double R_x = 0.67;//
        private double R_y = 0.33;
        private double G_x = 0.22;
        private double G_y = 0.71;

        private void btnBack_Click(object sender, EventArgs e)
        {
            MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(SerialPort1_DataReceived);//移除本窗口串口处理函数
            MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);//
            MainForm.Show();
            this.Hide();
        }

        private void FT2388_RegWR_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Int32 DataNum;
            string strLine = Convert.ToString(FT2388_txtRegData.Text);
            string[] arr = strLine.Split(','); //以逗号分割，添加到数组

            switch (btnTmp.Name)
            {
                case "FT2388_RegW":
                    {
                        Setting.TempRecord.cmdLen = arr.Length + 5;
                        Send_buf = new byte[arr.Length + 5];
                        Send_buf[0] = 0x53;
                        Send_buf[1] = 0x01;
                        Send_buf[2] = byte.Parse(arr.Length.ToString());
                        for (int i = 0; i < arr.Length; i++)
                        {
                            Send_buf[3 + i] = byte.Parse((Convert.ToInt32(arr[i], 16)).ToString());
                        }
                        CRCData.CalculateCrc16(Send_buf, out Send_buf[5 + arr.Length - 2], out Send_buf[5 + arr.Length - 1]);
                        try
                        {
                            MainForm.comPort.Write(Send_buf, 0, 5 + arr.Length);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                        }
                    }
                    break;

                case "FT2388_RegR":
                    {
                        Setting.TempRecord.NT37710CmdType = 0x02;
                        try
                        {
                            DataNum = Convert.ToInt32(FT2388_txtDataNum.Text) + 1;
                            Setting.TempRecord.cmdLen = DataNum + 5;
                            Send_buf = new byte[DataNum + 5];
                            Send_buf[0] = 0x53;
                            Send_buf[1] = 0x02;
                            Send_buf[2] = byte.Parse(Convert.ToString(DataNum));
                            Send_buf[3] = byte.Parse((Convert.ToInt32(arr[0], 16)).ToString());
                            CRCData.CalculateCrc16(Send_buf, out Send_buf[5 + DataNum - 2], out Send_buf[5 + DataNum - 1]);
                        }
                        catch
                        {
                            MessageBox.Show("读取长度有误，请检查", "错误");
                            break;
                        }
                        try
                        {
                            MainForm.comPort.Write(Send_buf, 0, 5 + DataNum);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                        }
                    }
                    break;

                case "otp":
                    {
                        Setting.TempRecord.cmdLen = arr.Length + 5;
                        Send_buf = new byte[arr.Length + 5];
                        Send_buf[0] = 0x53;
                        Send_buf[1] = 0x05;
                        Send_buf[2] = byte.Parse(arr.Length.ToString());
                        for (int i = 0; i < arr.Length; i++)
                        {
                            Send_buf[3 + i] = byte.Parse((Convert.ToInt32(arr[i], 16)).ToString());
                        }
                        CRCData.CalculateCrc16(Send_buf, out Send_buf[5 + arr.Length - 2], out Send_buf[5 + arr.Length - 1]);
                        try
                        {
                            MainForm.comPort.Write(Send_buf, 0, 5 + arr.Length);
                        }
                        catch
                        {
                            MessageBox.Show("串口有误，请检查", "错误");
                        }
                    }
                    break;

                default: break;
            }
            T1.Enabled = false;
            T1.Interval = 2000;
            T1.Enabled = true;
        }

        private void FT2388_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            btnBack_Click(btnBack, e);
        }

        private void FT2388_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible == true) //子窗体已开启标识
            {
                //MainForm.comPort.Close();
                //Thread.Sleep(5);
                MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);

                Thread.Sleep(5);
                MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
                Thread.Sleep(5);
                //MainForm.comPort.Open();
                txttip.Text += "com 已经连接！\r\n";
            }
            else
            {

            }
        }

        byte[,] GP;
        //Gamma RGB 默认初始值
        private int[,] GVs = { { 0,612,760,922,1034,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,2047},
                                        { 0,612,760,922,1034,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,2047},
                                        { 0,612,760,922,1034,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,2047} };
        private void CheckandCorrectGammaValue() //检查Gamma帮点寄存器的值是否存在高低灰阶反转，若有则强制修正；
        {
            byte i, j;
            for (j = 0; j < 3; j++)
            {
                for (i = 0; i < 31 - 1; i++)  //从第2个数开始检查至
                {
                    if (GVs[j, 30 - i - 1] > GVs[j, 30 - i])
                    {
                        GVs[j, 30 - i - 1] = (GVs[j, 30 - i] - 1);
                    }
                    if (GVs[j, 30 - i - 1] < 1)
                    {
                        GVs[j, 30 - i - 1] = 1;
                    }
                }
            }
        }
        byte regGammaIDLEmode = 0x38;  //IDLE disable     0x39:enable
        byte regGammaHBMmode = 0x00;    //HBM disable  0xc0:enable
        byte regGammaaddr1 = 0xe2; byte regGammaaddr2 = 0xe5; byte regGammaaddr3 = 0xe8;  //Normar Mode addr
        void GammaValueSet()
        {
            byte[] TepArr;
            TepArr = new byte[] { 
                // Normal mode	
                // idle mode disable	
                    1,regGammaIDLEmode,
                    2, 0X00, 0X00,
                    2,0x53,regGammaHBMmode,
                    //-------------------------Gamma R------
                    2, 0X00, 0X00,
                    6,regGammaaddr1,GP[0,0],GP[0,1],GP[0,2],GP[0,3],GP[0,4],
                    2, 0X00, 0X05,
                    6,regGammaaddr1,GP[0,5],GP[0,6],GP[0,7],GP[0,8],GP[0,9],
                    2, 0X00, 0X0a,
                    6,regGammaaddr1,GP[0,10],GP[0,11],GP[0,12],GP[0,13],GP[0,14],
                    2, 0X00, 0X0f,
                    6,regGammaaddr1,GP[0,15],GP[0,16],GP[0,17],GP[0,18],GP[0,19],
                    2, 0X00, 0X14,
                    6,regGammaaddr1,GP[0,20],GP[0,21],GP[0,22],GP[0,23],GP[0,24],
                    2, 0X00, 0X19,
                    6,regGammaaddr1,GP[0,25],GP[0,26],GP[0,27],GP[0,28],GP[0,29],
                    2, 0X00, 0X1e,
                    6,regGammaaddr1,GP[0,30],GP[0,31],GP[0,32],GP[0,33],GP[0,34],
                    2, 0X00, 0X23,
                    6,regGammaaddr1,GP[0,35],GP[0,36],GP[0,37],GP[0,38],GP[0,39],
                    2, 0X00, 0X28,
                    6,regGammaaddr1,GP[0,40],GP[0,41],GP[0,42],GP[0,43],GP[0,44],
                    2, 0X00, 0X2d,
                    3,regGammaaddr1,GP[0,45],GP[0,46],
                    //-------------------------Gamma GG------
                    2, 0X00, 0X00,
                    6,regGammaaddr2,GP[1,0],GP[1,1],GP[1,2],GP[1,3],GP[1,4],
                    2, 0X00, 0X05,
                    6,regGammaaddr2,GP[1,5],GP[1,6],GP[1,7],GP[1,8],GP[1,9],
                    2, 0X00, 0X0a,
                    6,regGammaaddr2,GP[1,10],GP[1,11],GP[1,12],GP[1,13],GP[1,14],
                    2, 0X00, 0X0f,
                    6,regGammaaddr2,GP[1,15],GP[1,16],GP[1,17],GP[1,18],GP[1,19],
                    2, 0X00, 0X14,
                    6,regGammaaddr2,GP[1,20],GP[1,21],GP[1,22],GP[1,23],GP[1,24],
                    2, 0X00, 0X19,
                    6,regGammaaddr2,GP[1,25],GP[1,26],GP[1,27],GP[1,28],GP[1,29],
                    2, 0X00, 0X1e,
                    6,regGammaaddr2,GP[1,30],GP[1,31],GP[1,32],GP[1,33],GP[1,34],
                    2, 0X00, 0X23,
                    6,regGammaaddr2,GP[1,35],GP[1,36],GP[1,37],GP[1,38],GP[1,39],
                    2, 0X00, 0X28,
                    6,regGammaaddr2,GP[1,40],GP[1,41],GP[1,42],GP[1,43],GP[1,44],
                    2, 0X00, 0X2d,
                    3,regGammaaddr2,GP[1,45],GP[1,46]
                       };
            //Thread.Sleep(200);
            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
            // Thread.Sleep(200);
            //--------------------------------------------------------------------------------------------------------
            TepArr = new byte[] { 
                // Normal mode	
                // idle mode disable	      
                    //1,0x38,
                    //2, 0X00, 0X00,
                    //2,0x53,0x00,                    
                     //-------------------------Gamma BBB-----
                    2, 0X00, 0X00,
                    6,regGammaaddr3,GP[2,0],GP[2,1],GP[2,2],GP[2,3],GP[2,4],
                    2, 0X00, 0X05,
                    6,regGammaaddr3,GP[2,5],GP[2,6],GP[2,7],GP[2,8],GP[2,9],
                    2, 0X00, 0X0a,
                    6,regGammaaddr3,GP[2,10],GP[2,11],GP[2,12],GP[2,13],GP[2,14],
                    2, 0X00, 0X0f,
                    6,regGammaaddr3,GP[2,15],GP[2,16],GP[2,17],GP[2,18],GP[2,19],
                    2, 0X00, 0X14,
                    6,regGammaaddr3,GP[2,20],GP[2,21],GP[2,22],GP[2,23],GP[2,24],
                    2, 0X00, 0X19,
                    6,regGammaaddr3,GP[2,25],GP[2,26],GP[2,27],GP[2,28],GP[2,29],
                    2, 0X00, 0X1e,
                    6,regGammaaddr3,GP[2,30],GP[2,31],GP[2,32],GP[2,33],GP[2,34],
                    2, 0X00, 0X23,
                    6,regGammaaddr3,GP[2,35],GP[2,36],GP[2,37],GP[2,38],GP[2,39],
                    2, 0X00, 0X28,
                    6,regGammaaddr3,GP[2,40],GP[2,41],GP[2,42],GP[2,43],GP[2,44],
                    2, 0X00, 0X2d,
                    3,regGammaaddr3,GP[2,45],GP[2,46]
                    };  //byte[] TepArr;
            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        void GValue_Format_set()  //把Gamma RGB的寄存器值转换为便于写入DDIC 的格式
        {
            int i, j, temp_cal;
            GP = new byte[3, 47];

            for (j = 0; j < 3; j++)
            {
                temp_cal = 0;
                for (i = 0; i < 47; i++)
                {
                    if (i % 3 == 0) // 0, 3, 6, 9, 12, ...									
                    {
                        if (i != 45)
                        {
                            GP[j, i] = (byte)(((GVs[j, temp_cal] & 0x0700) >> 4) + ((GVs[j, temp_cal + 1] / 256) & 0x07));
                            GP[j, i + 1] = (byte)(GVs[j, temp_cal] % 256);
                            GP[j, i + 2] = (byte)(GVs[j, temp_cal + 1] % 256);
                        }
                        else
                        {
                            GP[j, i] = (byte)((GVs[j, temp_cal] & 0x0700) >> 4);
                            GP[j, i + 1] = (byte)(GVs[j, temp_cal] % 256);
                        }
                        temp_cal = temp_cal + 2; // 0, 2, 4, 6, 8, ...								
                    }
                }
            }
        }
        byte rstep = 16; byte gstep = 16; byte bstep = 16;
        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
            txtTimeShow.Text = string.Format("{0:00}:{1:00}:{2:00}", TimeCount.Hours, TimeCount.Minutes, TimeCount.Seconds);
        }
        #endregion
        private int[] Point_FT2388 = new int[31] {//---Gamma绑点数据，这里的数据仅供参考---
            0,1,3,7,11,15,19,23,27,31,35,39,43,47,55,63,71,79,95,111,127,143,159,175,191,207,223,239,247,251,255};
        private void btnAutoGammas_FT3288_Click(object sender, EventArgs e)
        {
            int flag = 1;
            double Lr_d, Lg_d, Lb_d;
            D_lums = new double[31, 3];
            D_lum = new double[31];
            index = 1;

            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));

            TimTest.Start();
            TimeNow = DateTime.Now; //开始计时

            for (int i = 0; i < 31; i++)
            {
                D_lum[i] = (Math.Pow((Point_FT2388[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
            }

            D_x = Convert.ToDouble(txtVT_x.Text);
            D_y = Convert.ToDouble(txtVT_y.Text);
            Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
            Lb_d = 1.0;
            Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

            for (int i = 0; i < 31; i++)
            {
                D_lums[i, 0] = D_lum[i] * Lr_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 1] = D_lum[i] * Lg_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 2] = D_lum[i] * Lb_d / (Lr_d + Lg_d + Lb_d);
            }

            switch (flag)
            {
                case 1://寄存器值与亮度正比
                    {
                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                        x_off = Convert.ToDouble(txtVT_xoff.Text);
                        y_off = Convert.ToDouble(txtVT_yoff.Text);
                        OLED_Show_Click(btnwhite, e);
                        //ReceivOKFlag = false;
                        T17.Enabled = true;
                    }
                    break;
                case 2:  //寄存器值与亮度反比
                    break;
                default:
                    break;
            }
        }
        bool lastdirupR = true; bool lastdirupG = true; bool lastdirupB = true; // Gamma 调整方向
        private void T17_Tick(object sender, EventArgs e)
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            T17.Enabled = false;
            T17.Interval = 200;

            Msr_CA310();

            txtlvshow.Text = "Lv: " + auto_lum + "\r\n" + "x: " + auto_x + "\r\n" + "y: " + auto_y + "\r\n";
            // if (index > 2)
            labTargetlum.Text = "Tar:" + D_lum[31 - index];

            Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
            Lb_t = 1.0;
            Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
            lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
            lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
            lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);

            lum_off = (D_lum[31 - index] * Convert.ToDouble(numVT_loff.Value) / 1000);
            x_off = Convert.ToDouble(txtVT_xoff.Text);
            y_off = Convert.ToDouble(txtVT_yoff.Text);

            if ((auto_lum < (D_lum[31 - index] + lum_off)) && (auto_lum > (D_lum[31 - index] - lum_off)))//
                flag1 = 0;
            if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                flag2 = 0;
            if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                flag3 = 0;

            if (flag1 == 0 && flag2 == 0 && flag3 == 0)
            {
                T17.Enabled = false;
                index++;
                rstep = (byte)(int.Parse(numStep.Value.ToString()));
                gstep = (byte)(int.Parse(numStep.Value.ToString()));
                bstep = (byte)(int.Parse(numStep.Value.ToString()));
                if (index == 31)
                {
                    TimTest.Stop();//停止计时
                    txttip.Text = txttip.Text + "FT2388 Gamma调试完毕!\r\n";
                    txttip.Focus();//获取焦点
                    txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                    txttip.ScrollToCaret();//滚动到光标处
                    //FirstAdjGammaFlag = true;
                    return;
                }
                if (index < 31)
                {
                    txttip.Text += index + "" + "完成...";
                    txttip.Select(txttip.Text.Length, 0);
                    txttip.ScrollToCaret();

                    Thread.Sleep(10); //1秒=1000毫秒，
                    //T17.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }
                numPatternR.Value = Point_FT2388[31 - index];
                numPatternG.Value = Point_FT2388[31 - index];
                numPatternB.Value = Point_FT2388[31 - index];
                OLED_Show_Click(btnPatternW, e);//写入Pattern参数
                //ReceivOKFlag = false;
                Thread.Sleep(100);
                T17.Enabled = true;
            }
            else
            {
                {
                    step_l = (byte)(int.Parse(numStep.Value.ToString()));
                    switch (index)
                    {
                        //case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 14:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 20:
                        case 21:
                        case 22:
                        case 23:
                        case 24:
                        case 25:
                        case 26:
                        case 27:
                        case 28:
                        case 29:
                        case 30:
                            {
                                if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))
                                {
                                    {//Gamma R
                                        if (lumr > D_lums[31 - index, 0])
                                        {
                                            if ((!lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                            GVs[0, 31 - index] = GVs[0, 31 - index] - rstep;// (byte)(int.Parse(numStep.Value.ToString()));
                                            lastdirupR = true;
                                            // rstep = 16;
                                        }

                                        else
                                        {
                                            if ((lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                            GVs[0, 31 - index] = GVs[0, 31 - index] + rstep;
                                            lastdirupR = false;
                                            //rstep = 32;
                                        }
                                        if (GVs[0, 31 - index] < 1)
                                        {
                                            GVs[0, 31 - index] = 1;
                                        }
                                    }

                                    {//Gamma GG
                                        {
                                            if (lumg > D_lums[31 - index, 1])
                                            {
                                                if ((!lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                                GVs[1, 31 - index] = GVs[1, 31 - index] - gstep;
                                                lastdirupG = true;
                                            }
                                            else
                                            {
                                                if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                                GVs[1, 31 - index] = GVs[1, 31 - index] + gstep;
                                                lastdirupG = false;
                                            }
                                            if (GVs[1, 31 - index] < 1)
                                            {
                                                GVs[1, 31 - index] = 1;
                                            }
                                        }

                                    }

                                    {   ////Gamma BBB
                                        if (lumb > D_lums[31 - index, 2])
                                        {
                                            if ((!lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                            GVs[2, 31 - index] = GVs[2, 31 - index] - bstep;
                                            lastdirupB = true;
                                        }
                                        else
                                        {
                                            if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                            GVs[2, 31 - index] = GVs[2, 31 - index] + bstep;
                                            lastdirupB = false;
                                        }
                                        if (GVs[2, 31 - index] < 1)
                                        {
                                            GVs[2, 31 - index] = 1;
                                        }
                                        txttip.Text += "rstep:" + rstep + "gstetp:" + gstep + "bstep:" + bstep + "\r\n";
                                        txttip.Select(txttip.Text.Length, 0);
                                        txttip.ScrollToCaret();
                                    }
                                }

                                CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱                                

                                txtGammaValue.Text = GVs[0, 31 - index] + "\r\n" + GVs[1, 31 - index] + "\r\n" + GVs[2, 31 - index] + "\r\n";

                                GValue_Format_set();  //Gamma 值与实际地址进行转换
                                if (!MainForm.comPort.IsOpen)
                                {
                                    try
                                    {
                                        MainForm.comPort.PortName = Detection.GetComNum();
                                        MainForm.comPort.BaudRate = Setting.ComSet.comBaudRate;
                                        MainForm.openSerialPort(true);
                                    }
                                    catch
                                    {
                                        MessageBox.Show("没有搜索到串口！", "错误提示");
                                        return;
                                    }
                                }
                                GammaValueSet();
                                Thread.Sleep(100);
                                Application.DoEvents();//重点，必须加上，否则父子窗体都假死                               
                            }
                            break;
                        case 31:
                            {
                                T17.Enabled = false;
                            }
                            break;

                        default:
                            T17.Enabled = false;
                            break;
                    }
                    System.Threading.Thread.Sleep(10);
                }
                T17.Enabled = true;
            }
        }

        private void btn_FT3288_Stop_Click(object sender, EventArgs e)
        {
            T17.Stop();
            TimTest.Stop();
        }

        private void btnSaveGamma_Click(object sender, EventArgs e)
        {
            {
                Button btnTmp = (Button)sender;
                switch (btnTmp.Name)
                {
                    case "btnSaveGamma":
                        {
                            //--------------------保存云英谷格式----------------------------
                            //以文本形式保存                            
                            {//保存
                                SaveFileDialog sf = new SaveFileDialog(); //对话框
                                sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

                                string str = "灰阶序号,灰阶亮度,reg_R,reg_G,reg_B\r\n";
                                if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                                {
                                    if (sf.FileName == "") return; //如果没有输入文件名
                                    try
                                    {
                                        StreamWriter sw = null; //文件流
                                        sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                        for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                        {
                                            str = str + this.GammaReg_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString() + "\r\n";
                                        }
                                        sw.WriteLine(str);
                                        sw.Dispose(); //释放资源
                                        sw.Close(); //关闭数据流
                                        MessageBox.Show("数据保存OK！", "系统提示：");

                                    }
                                    catch
                                    {
                                        MessageBox.Show("数据保存时发生错误，请再试！", "系统提示：");
                                    }
                                }

                            }
                        }
                        break;
                    case "btnLoadGamma":
                        {
                            this.GammaReg_dataGridView.Rows.Clear();
                            OpenFileDialog sf = new OpenFileDialog();
                            int Line_Count = 0;
                            string strtmp = "";
                            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            sf.Title = "数据导入";
                            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                            {
                                FileStream fs = new FileStream(sf.FileName, FileMode.Open, FileAccess.Read);
                                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                                string strLine = streamReader.ReadLine();
                                while (!string.IsNullOrEmpty(strLine))
                                {
                                    strtmp = strtmp + strLine + ",";
                                    strLine = streamReader.ReadLine(); //循环读取下一行
                                    Line_Count++;
                                }
                                fs.Close(); //关闭流
                                streamReader.Close();
                                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                                for (int j = 1; j <= Line_Count - 1; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                                try
                                {
                                    for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                    {
                                        GammaReg_dataGridView.Rows[i].Cells[0].Value = arrtmp[5 * (i + 1) + 0];
                                        GammaReg_dataGridView.Rows[i].Cells[1].Value = arrtmp[5 * (i + 1) + 1];
                                        GammaReg_dataGridView.Rows[i].Cells[2].Value = arrtmp[5 * (i + 1) + 2];
                                        GammaReg_dataGridView.Rows[i].Cells[3].Value = arrtmp[5 * (i + 1) + 3];
                                        GammaReg_dataGridView.Rows[i].Cells[4].Value = arrtmp[5 * (i + 1) + 4];
                                        //------------------------------------
                                        GVs[0, i] = Convert.ToInt16(arrtmp[(5 * (i + 1)) + 2]);
                                        GVs[1, i] = Convert.ToInt16(arrtmp[(5 * (i + 1)) + 3]);
                                        GVs[2, i] = Convert.ToInt16(arrtmp[(5 * (i + 1)) + 4]);
                                    }
                                    MessageBox.Show("数据导入OK！", "提示：");
                                }
                                catch
                                {
                                    MessageBox.Show("数据导入时发生错误！", "提示：");
                                }
                            }
                        }
                        break;
                    case "btn_CAS200_Clean":
                        {
                            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                            if (dr == DialogResult.OK)
                            {
                                this.GammaReg_dataGridView.Rows.Clear();
                            }
                        }
                        break;

                    default: break;
                }
            }
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            D_lum = new double[31];
            {
                this.GammaReg_dataGridView.Rows.Clear();
            }

            for (byte i = 0; i < 31; i++)
            {
                D_lum[i] = (Math.Pow((Point_FT2388[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
                DataGirdShow(i, GVs[0, i], GVs[1, i], GVs[2, i]);
            }
        }
        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;
            DataGridViewRow Row1 = new DataGridViewRow();
            Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.GammaReg_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.GammaReg_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.GammaReg_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.GammaReg_dataGridView.Rows.Add(Row1);
            }
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[1].Value = (D_lum[index]).ToString("#0.0000");
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[2].Value = RRR;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[3].Value = GGG;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
                this.GammaReg_dataGridView.Rows[Current_Index].Selected = false;
                this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            GammaReg_dataGridView.FirstDisplayedScrollingRowIndex = GammaReg_dataGridView.RowCount - 1;
        }

        #region //通用命令处理
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        MainForm.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend2":
                    {
                        MainForm.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend3":
                    {
                        MainForm.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {
                MainForm.SendCmd(0);
            }
            else
            {
                MainForm.SendCmd(4);
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }
        private void SaveCode_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Driver IC Code文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    if (ChkCMD1.Checked)
                    {
                        str += "//---CMD1---\r\n" + txtCmd1.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD2.Checked)
                    {
                        str += "//---CMD2---\r\n" + txtCmd2.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD3.Checked)
                    {
                        str += "//---CMD3---\r\n" + txtCmd3.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Driver IC Code保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver IC Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            txtCmd1.Clear();
                            txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion
        string path = "";

        private void btnFun1_Click(object sender, EventArgs e)
        {
            string tepstr = "";
            tepstr = txtCmd3.Text;
            txtCmd3.Text = txtFun1.Text;
            Send_Cmd_Click(btnSend3, e);
            txtCmd3.Text = tepstr;
        }

        private void btnFun2_Click(object sender, EventArgs e)
        {
            string tepstr = "";
            tepstr = txtCmd3.Text;
            txtCmd3.Text = txtFun2.Text;
            Send_Cmd_Click(btnSend3, e);
            txtCmd3.Text = tepstr;
        }

        private void btnFun3_Click(object sender, EventArgs e)
        {
            string tepstr = "";
            tepstr = txtCmd3.Text;
            txtCmd3.Text = txtFun3.Text;
            Send_Cmd_Click(btnSend3, e);
            txtCmd3.Text = tepstr;
        }

        private void btnFun4_Click(object sender, EventArgs e)
        {
            string tepstr = "";
            tepstr = txtCmd3.Text;
            txtCmd3.Text = txtFun4.Text;
            Send_Cmd_Click(btnSend3, e);
            txtCmd3.Text = tepstr;
        }

        private void btnCleartiptxt_Click(object sender, EventArgs e)
        {
            txttip.Clear();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            MainForm.btnRun_Click(MainForm.btnRun, e);
        }

        private void btnWriteGamma_Click(object sender, EventArgs e)
        {
            CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱    
            GValue_Format_set();  //Gamma 值与实际地址进行转换
            GammaValueSet();
        }

        private void btnGammaValueUpdate_Click(object sender, EventArgs e)
        {
            int Line_Count = 0;
            try
            {
                Line_Count = GammaReg_dataGridView.RowCount;
            }
            catch
            {
                MessageBox.Show("表格数据(行数)异常！", "提示：");
                return;
            }
            try
            {
                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                {
                    GVs[0, i] = Convert.ToInt16(GammaReg_dataGridView.Rows[i].Cells[2].Value);
                    GVs[1, i] = Convert.ToInt16(GammaReg_dataGridView.Rows[i].Cells[3].Value);
                    GVs[2, i] = Convert.ToInt16(GammaReg_dataGridView.Rows[i].Cells[4].Value);
                }
                //MessageBox.Show("数据更新OK！", "提示：");
                txttip.Text += "Gamma数据更新OK！\r\n";
                btnWriteGamma.PerformClick();
            }
            catch
            {
                MessageBox.Show("Gamma数据更新错误！", "唐韬说：");
            }
        }

        private void rdoGammaNormal_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoGammaNormal.Checked)
            {
                regGammaIDLEmode = 0x38;  //IDLE disable
                regGammaHBMmode = 0x00;    //HBM disable
                regGammaaddr1 = 0xe2; regGammaaddr2 = 0xe5; regGammaaddr3 = 0xe8;  //Normar Mode addr
            }
            else if (rdoGammaIDLE.Checked)
            {
                regGammaIDLEmode = 0x39;  //IDLE enable
                regGammaHBMmode = 0x00;    //HBM disable
                regGammaaddr1 = 0xe1; regGammaaddr2 = 0xe4; regGammaaddr3 = 0xe7;  //Normar Mode addr
            }
            else if (rdoGammaHBM.Checked)
            {
                regGammaIDLEmode = 0x38;  //IDLE disable
                regGammaHBMmode = 0xc0;    //HBM enable
                regGammaaddr1 = 0xe3; regGammaaddr2 = 0xe6; regGammaaddr3 = 0xe9;  //Normar Mode addr
            }
        }

        static byte[] GetCRCArray(byte[] arr, Byte speedflag)
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        //----------------------------------------------------------------------------------------------------------------------
        #region //------自定义功能按键---------------
        private void CustomSendCmd_Click(object sender, EventArgs e)   //自定义功能按键
        {
            Button btn = (Button)sender; string spedflag = "";
            switch (btn.Name)
            {
                case "btnFun1":
                    {
                        MainForm.txtProcessDrivercode(funcmd1, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag1;
                    }
                    break;
                case "btnFun2":
                    {
                        MainForm.txtProcessDrivercode(funcmd2, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag2;
                    }
                    break;
                case "btnFun3":
                    {
                        MainForm.txtProcessDrivercode(funcmd3, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag3;
                    }
                    break;
                case "btnFun4":
                    {
                        MainForm.txtProcessDrivercode(funcmd4, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag4;
                    }
                    break;
                case "btnFun5":
                    {
                        MainForm.txtProcessDrivercode(funcmd5, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag5;
                    }
                    break;
                case "btnFun6":
                    {
                        MainForm.txtProcessDrivercode(funcmd6, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag6;
                    }
                    break;
                case "btnFun7":
                    {
                        MainForm.txtProcessDrivercode(funcmd7, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag7;
                    }
                    break;
                case "btnFun8":
                    {
                        MainForm.txtProcessDrivercode(funcmd8, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag8;
                    }
                    break;

            }
            //Setting.TempRecord.cmdLen = 6;
            if (spedflag == "LP")
            {
                MainForm.SendCmd(0);  //低速
            }
            else
            {
                MainForm.SendCmd(4); //高速
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }

        string FunDefaultfilePath = "";
        string funcmd1, funcmd2, funcmd3, funcmd4, funcmd5, funcmd6, funcmd7, funcmd8;

        private void btnFunTestcmdSaveAS_Click(object sender, EventArgs e)
        {
            string tfilname = "FT2388Fun1.txt";
            if (rdoFun1.Checked) { tfilname = "FT2388Fun1.txt"; }
            else if (rdoFun2.Checked) { tfilname = "FT2388Fun2.txt"; }
            else if (rdoFun3.Checked) { tfilname = "FT2388Fun3.txt"; }
            else if (rdoFun4.Checked) { tfilname = "FT2388Fun4.txt"; }
            else if (rdoFun5.Checked) { tfilname = "FT2388Fun5.txt"; }
            else if (rdoFun6.Checked) { tfilname = "FT2388Fun6.txt"; }
            else if (rdoFun7.Checked) { tfilname = "FT2388Fun7.txt"; }
            else if (rdoFun8.Checked) { tfilname = "FT2388Fun8.txt"; }

            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            txt.FileName = tfilname;
            string str = "";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    {
                        str += txtFuncmd.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    //MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");
                    txttip.Text += tfilname + "命令导出保存OK，请确认文件名！" + "\r\n";
                    txttip.Select(txttip.Text.Length, 0);
                    txttip.ScrollToCaret();
                }
                catch
                {
                    MessageBox.Show("保存时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void btnFunEdit_Click(object sender, EventArgs e)
        {
            string tfilname = "FT2388Fun1.cfg";
            if (rdoFun1.Checked) { tfilname = "FT2388Fun1.cfg"; }
            else if (rdoFun2.Checked) { tfilname = "FT2388Fun2.cfg"; }
            else if (rdoFun3.Checked) { tfilname = "FT2388Fun3.cfg"; }
            else if (rdoFun4.Checked) { tfilname = "FT2388Fun4.cfg"; }
            else if (rdoFun5.Checked) { tfilname = "FT2388Fun5.cfg"; }
            else if (rdoFun6.Checked) { tfilname = "FT2388Fun6.cfg"; }
            else if (rdoFun7.Checked) { tfilname = "FT2388Fun7.cfg"; }
            else if (rdoFun8.Checked) { tfilname = "FT2388Fun8.cfg"; }
            else { MessageBox.Show("未指定按键"); return; }
            try
            {
                StreamReader streamReader = new StreamReader((Application.StartupPath + "\\x_Focaltech\\" + tfilname), Encoding.Default);
                txtFuncmd.Text = streamReader.ReadToEnd();
                streamReader.Dispose();
                streamReader.Close();
            }
            catch
            {
                MessageBox.Show("保存命令时发生错误，请再试！", "系统提示：");
            }
        }

        private void btnPreproccess_Click(object sender, EventArgs e)
        {
            string acmd = "";
            acmd = txtFuncmd.Text;
            acmd = acmd.Replace("0x", "");
            acmd = acmd.Replace("0X", "");
            acmd = acmd.Replace("REGW", "");
            acmd = acmd.Replace("regw", "");
            txtFuncmd.Text = acmd;

            string str = "";
            foreach (string s2 in txtFuncmd.Lines)
            {
                if (s2 == "")
                {
                    continue;
                }
                str += s2.Trim() + "\r\n";
            }
            txtFuncmd.Text = str;
        }

        private void btnFunexport_Click(object sender, EventArgs e)
        {
            rdoFun1.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun2.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun3.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun4.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun5.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun6.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun7.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun8.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
        }

        //------------------------------------------------------------
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            path = Application.StartupPath + "\\x_Focaltech";
            try
            {
                //StreamReader streamReader = new StreamReader(path+"\\Fun1.txt", Encoding.Default);
                //FunDefaultfilePath = streamReader.ReadLine();
                //streamReader.Close();
                ReadFuncfg(path + "\\FT2388Fun1.cfg", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1;

                ReadFuncfg(path + "\\FT2388Fun2.cfg", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2;

                ReadFuncfg(path + "\\FT2388Fun3.cfg", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3;

                ReadFuncfg(path + "\\FT2388Fun4.cfg", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4;

                ReadFuncfg(path + "\\FT2388Fun5.cfg", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5;

                ReadFuncfg(path + "\\FT2388Fun6.cfg", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6;

                ReadFuncfg(path + "\\FT2388Fun7.cfg", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7;

                ReadFuncfg(path + "\\FT2388Fun8.cfg", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8;
                //btnStore.Enabled = true;
                txttip.Text += "按键功能刷新完成" + "\r\n";
                //MessageBox.Show("刷新完成", "向东说");
            }
            catch
            {
                MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
        }

        private void btnStore_Click(object sender, EventArgs e)
        {
            string str = "";
            {
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun1.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun1.Text + "\r\n";//
                        str += speedflag1 + "\r\n";
                        str += funcmd1;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun2.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun2.Text + "\r\n";//
                        str += speedflag2 + "\r\n";
                        str += funcmd2;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun3.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun3.Text + "\r\n";//
                        str += speedflag3 + "\r\n";
                        str += funcmd3;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun4.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun4.Text + "\r\n";//
                        str += speedflag4 + "\r\n";
                        str += funcmd4;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun5.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun5.Text + "\r\n";//
                        str += speedflag5 + "\r\n";
                        str += funcmd5;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun6.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun6.Text + "\r\n";//
                        str += speedflag6 + "\r\n";
                        str += funcmd6;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun7.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun7.Text + "\r\n";//
                        str += speedflag7 + "\r\n";
                        str += funcmd7;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\FT2388Fun8.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun8.Text + "\r\n";//
                        str += speedflag8 + "\r\n";
                        str += funcmd8;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    MessageBox.Show("向东说固化命令成功！", "系统提示：");
                    btnRefresh.Enabled = true;
                    btnStore.Enabled = false;
                }
                catch
                {
                    MessageBox.Show("固化命令时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void btnFunTestcmdSend_Click(object sender, EventArgs e)
        {
            if (chkFunpreproccess.Checked) { btnPreproccess.PerformClick(); }
            String[] lines = txtFuncmd.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string speedflag = lines[1];
            String text = "";
            for (int i = 0; i < lines.Length; i++)
            {
                //假设删除第2行第3行
                if (i == 0 || i == 1)
                {
                    continue;
                }
                text += lines[i] + (i == lines.Length - 1 ? "" : "\r\n"); //最后一行不添加换行符
            }
            MainForm.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
            if (speedflag == "LP")
            {
                MainForm.SendCmd(0);  //低速
            }
            else
            {
                MainForm.SendCmd(4); //高速
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }

        private void btnFunTestcmdSave_Click(object sender, EventArgs e)
        {
            string str = "";
            string tpath = Application.StartupPath + "\\x_Focaltech";
            string tfilname = "FT2388Fun1.cfg";
            if (rdoFun1.Checked) { tfilname = "FT2388Fun1.cfg"; }
            else if (rdoFun2.Checked) { tfilname = "FT2388Fun2.cfg"; }
            else if (rdoFun3.Checked) { tfilname = "FT2388Fun3.cfg"; }
            else if (rdoFun4.Checked) { tfilname = "FT2388Fun4.cfg"; }
            else if (rdoFun5.Checked) { tfilname = "FT2388Fun5.cfg"; }
            else if (rdoFun6.Checked) { tfilname = "FT2388Fun6.cfg"; }
            else if (rdoFun7.Checked) { tfilname = "FT2388Fun7.cfg"; }
            else if (rdoFun8.Checked) { tfilname = "FT2388Fun8.cfg"; }
            else { MessageBox.Show("未指定按键"); return; }
            try
            {
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(Application.StartupPath + "\\x_Focaltech\\" + tfilname, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                {
                    str = txtFuncmd.Text;
                }
                sw.Write(str);
                sw.Dispose(); //释放资源
                sw.Close(); //关闭数据流
                            // MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");

                MessageBox.Show(tfilname + "保存命令成功！", "向东说：");
                btnRefresh.Enabled = true;
                btnStore.Enabled = false;
                btnRefresh.PerformClick();
            }
            catch
            {
                MessageBox.Show("保存命令时发生错误，请再试！", "系统提示：");
            }
        }
        string speedflag1, speedflag2, speedflag3, speedflag4, speedflag5, speedflag6, speedflag7, speedflag8;

        private void btnFunLoad_Click(object sender, EventArgs e)
        {
            int num = 0;
            {
                StreamReader streamReader = new StreamReader("./update/Fun.cfg", Encoding.Default);
                FunDefaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (FunDefaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = FunDefaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            FunDefaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }

            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Fun.cfg", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(FunDefaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
            // -------------------------------------------------------------------------
            try
            {
                ReadFuncfg(path + "\\FT2388Fun1.txt", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\FT2388Fun2.txt", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\FT2388Fun3.txt", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\FT2388Fun4.txt", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\FT2388Fun5.txt", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\FT2388Fun6.txt", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\FT2388Fun7.txt", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\FT2388Fun8.txt", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            btnStore.Enabled = true;
            if (num < 8)
            {
                MessageBox.Show("完成" + num + "个配置，部分按键配置文件缺失，请检查", "向东提示");
            }

        }
        private void ReadFuncfg(string addr, out String Ftitle, out String speedflag, out String Fcmd)
        {
            lines = new List<string>();

            FileStream fs = new FileStream(addr, FileMode.Open);
            StreamReader rd = new StreamReader(fs);
            string s;
            //读入文件所有行，存放到List<string>集合中
            while ((s = rd.ReadLine()) != null)
            {
                lines.Add(s);
            }
            rd.Close();
            fs.Close();
            //第一行在txttip中显示
            Ftitle = "";
            speedflag = "";
            if (lines.Count > 0)
            {
                Ftitle = lines[0];
                speedflag = lines[1];
            }
            //txtFuncmd.Text = "";
            Fcmd = "";
            for (int i = 2; i < lines.Count; i++)
            {
                Fcmd += lines[i] + "\r\n";
            }

        }
        #endregion


    }
}
